package com.leff.cards.request;

import com.leff.cards.Dictionary;
import com.leff.cards.StoreWrapper;
import com.leff.cards.entity.Group;
import com.leff.cards.entity.User;

public class SubmitCard extends Request {

	public SubmitCard(Dictionary dict) {
		super(dict);
	}
	
	public RequestResult doSubmit() {
		
		RequestResult result = this.verifyRequiredParameters(Parameter.GROUP_ID, Parameter.ID, Parameter.CARD_IDS);
		if(!result.isSuccessful()) {
			return result;
		}
		
		// Fetch the group
		long groupId = Long.valueOf(mDictionary.get(Parameter.GROUP_ID).toString());
		Group G = StoreWrapper.getGroupById(groupId);
		
		if(G == null) {
			result.setErrorResult("No group found with ID " + groupId);
			return result;
		}
		
		// Fetch the user
		String userIdString = mDictionary.get(Parameter.ID).toString();
		long userId = Long.valueOf(userIdString);
		User U = StoreWrapper.getUserById(userId);
		
		if(U == null) {
			result.setErrorResult("No user found with ID " + groupId);
			return result;
		}
		
		String cardsString = (String)mDictionary.get(Parameter.CARD_IDS);
		
		G.submitCards(cardsString, userIdString);
		StoreWrapper.store(G);
		
		result.setSuccessMessage("Successfully submitted cards to group " + G.getName());
		
		return result;
	}
}
